from django.contrib.auth.models         import Group,Permission
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions             import ObjectDoesNotExist
from sitepal.sitebase.management.setup  import register,ObjectSetup,ListSetup
#from sitepal.sitebase.models            import Property

class PermissionSetup(ObjectSetup):
    def __init__(self):
        ObjectSetup.__init__(self,"permissions",Permission.objects)

    def syncobject(self,name,data):
        try:
            app_label,model,codename = name.split('.')
        except ValueError:
            raise ValueError,"Permission name must be given as <app_label>.<model>.<codename>"
        try:
            obj = self.manager.get_by_natural_key(codename,app_label,model)
        except ObjectDoesNotExist:
            obj              = Permission()
            obj.codename     = codename
            obj.content_type = ContentType.objects.get_by_natural_key(app_label,model)
        obj.name = data['content']
        return obj

class GroupSetup(ObjectSetup):
    def __init__(self):
        ObjectSetup.__init__(self,"groups",Group.objects,save_on_init=True,allow_resync=True)

    def get_permission(self,name):
        try:
            app_label,model,codename = name.split('.')
            return Permission.objects.get_by_natural_key(codename,app_label,model)
        except ValueError:
            raise ValueError,"Permission name must be given as <app_label>.<model>.<codename>"
        except ObjectDoesNotExist:
            raise ValueError,"Unknown permission '{0}'".format(name)

    def syncobject(self,name,data):
        obj = self.initobject(name,data)
        for perm_name in data['items']:
            obj.permissions.add(self.get_permission(perm_name))
        return obj

#class PropertySetup(ObjectSetup):
#    def __init__(self):
#        ObjectSetup.__init__(self,"properties",Property.objects)
#    
#    def syncobject(self,name,data):
#        obj                = self.initobject(name,data)
#        obj.origin         = data['_app_name_']
#        obj.value          = data.get('value')
#        obj.to_python_name = data.get('to_python')
#        obj.to_string_name = data.get('to_string')
#        if 'validators' in data:
#            names = data['validators']
#            if isinstance(names,basestring):
#                obj.validator_names = names
#            elif isinstance(names,(tuple,list)):
#                obj.validator_names = ",".join(names)
#            else:
#                raise ValueError,"Property '{0}': Validators must be a string or list".format(obj.name)
#        return obj

class SiteBaseSetup(ListSetup):
    def __init__(self):
        ListSetup.__init__(self,"site base",GroupSetup(),PropertySetup())
#        ListSetup.__init__(self,"site base",PermissionSetup(),GroupSetup(),PropertySetup())

register(SiteBaseSetup())
